const fs = require("fs");
const hx = require("hbuilderx");
const ci = require('miniprogram-ci');
const st = require("./setting.js");

async function upload(params) {
	
	// console.log("params@@", params);
	let text1 = "正在准备项目...";
	let text2 = "开始上传项目到微信平台...";
	let text3 = "上传项目到微信平台成功";
	let textError = "上传项目到微信平台失败";
	let textUrl = '上传项目到微信平台成功,访问地址:https://mp.weixin.qq.com';

	let appid = params.appid;
	let buildPath = params.buildClientPath;
	let privatekey = params.privatekey;
	let version = params.version;
	let description = params.description;
	let clientId = params.clientId;

	// 创建输出通道
	let outputChannel;
	if (!clientId) {
		outputChannel = hx.window.createOutputChannel("HBuilder");
	}

	if (buildPath && fs.existsSync(buildPath)) {
		// 打印准备日志
		if (clientId) {
			hx.cliconsole.log({
				clientId: clientId,
				msg: text1,
				status: "info"
			});
		} else {
			outputChannel.appendLine(text1);
		}
		// 构建一个项目
		try {
			const project = new ci.Project({
				appid: appid,
				type: 'miniProgram',
				projectPath: buildPath,
				privateKeyPath: privatekey,
				ignores: ['node_modules/**/*'],
			})

			// 打印开始上传日志
			if (clientId) {
				hx.cliconsole.log({
					clientId: clientId,
					msg: text2,
					status: "info"
				});
			} else {
				outputChannel.appendLine(text2);
			}
			
			// 上传项目
			const uploadResult = await ci.upload({
				project,
				version: version,
				desc: description,
				setting: st.setting(buildPath),
				onProgressUpdate: async (data) => {
					if (clientId) {
						hx.cliconsole.log({
							clientId: clientId,
							msg: data.message,
							status: "info"
						});
					} else {
						outputChannel.appendLine(data.message);
					}
				}
			})
			
			if (clientId) {
				hx.cliconsole.log({
					clientId: clientId,
					msg: text3,
					status: "Error"
				});
			} else {
				outputChannel.appendLine(textUrl);
			}
		} catch (e) {
			if (clientId) {
				hx.cliconsole.log({
					clientId: clientId,
					msg: textError,
					status: "Info"
				});
				hx.cliconsole.log({
					clientId: clientId,
					msg: e.toString(),
					status: "Error"
				});
			} else {
				outputChannel.appendLine({
					line:textError,
					level:"error"
				});
				outputChannel.appendLine({
					line:e.toString(),
					level:"error"
				});
			}
		}

	} else {
		if (clientId) {
			hx.cliconsole.log({
				clientId: clientId,
				msg: '',
				status: "Error"
			});
		}
	}
}

// 导出
module.exports = {
	upload: upload
}
